package yxy.game.pm2.module.conquest;

import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.targetreward;
import yxy.cherry.data.bean.task;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.task.Task;

import java.util.ArrayList;
import java.util.Map;

public class TargetTaskModule extends PlayerModule {
	// bean===========================================================================

	private ArrayList<String> taskCodes = new ArrayList<>();

	public ArrayList<String> getTaskCodes() {
		return taskCodes;
	}

	public void setTaskCodes(ArrayList<String> taskCodes) {
		this.taskCodes = taskCodes;
	}

	// redis==========================================================================
	private static String key(String playerCode) {
		return String.format("PLAYER:%s:MODULE:CONQUEST_TARGET", playerCode);
	}

	public void set() {
		try {
			setv(key(getPlayerCode()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	static public TargetTaskModule get(String playerCode) {
		try {
			TargetTaskModule module = getv(key(playerCode));
			if (module == null) {
				module = MySQLCacheDAO.getV(key(playerCode), TargetTaskModule.class);
				if(module != null){module.set();}//把数据同步到redis
			}

			if (module == null) {
				module = create(playerCode);
			}
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	static private TargetTaskModule create(String playerCode) {
		TargetTaskModule module = new TargetTaskModule();
		module.setPlayerCode(playerCode);
		{
			Map<String, targetreward> datas = DataCenter.getAllData(targetreward.class);
			for (targetreward data : datas.values()) {
				if (data.getLevel() == 1) {
					targetreward temp = data;
					while (temp != null) {
						task taskdata = DataCenter.getData(temp.getTaskid(), task.class);
						Task task = Task.create(playerCode, taskdata);
						module.getTaskCodes().add(task.getCode());
						temp = datas.get(String.valueOf(temp.getFrontid()));
					}
					break;
				}
			}
		}
		module.set();
		return module;
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				TargetTaskModule module = getv(key(playerCode));
				MySQLCacheDAO.setV(key, module);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}

}
